package main.java.utils.hxy.thread.thread;


import java.util.concurrent.CountDownLatch;
import java.util.function.Consumer;

/**
 * @author kreo
 * @date 2020-4-21 13:09:10
 */
public class IRunnable<T> {
    private boolean withContext = false;
    private T data;
    private Consumer<T> consumer;

    public IRunnable setWithContext(boolean withContext) {
        this.withContext = withContext;
        return this;
    }

    public IRunnable setData(T data) {
        this.data = data;
        return this;
    }

    public IRunnable setExecute(Consumer<T> consumer, CountDownLatch latch) {
        this.consumer = latchConsumer(consumer, latch);
        return this;
    }

    public IRunnable setExecute(Consumer<T> consumer) {
        this.consumer = consumer;
        return this;
    }


    public Runnable runnable() {
        Runnable runnable = () -> consumer.accept(data);
        if (withContext) {
            return IContextRunnable.runnable(runnable);
        } else {
            return runnable;
        }
    }

    /**
     * 消费者转换 , 把普通的消费者,改成CountDownLatch的消费者
     *
     * @param consumer
     * @return
     */
    private Consumer<T> latchConsumer(Consumer<T> consumer, CountDownLatch latch) {
        return p -> {
            consumer.accept(p);
            latch.countDown();
        };
    }

}
